package com.depository.oss.controller;

import com.depository.oss.model.entity.User;
import com.depository.oss.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/queryForPage", method = {RequestMethod.GET, RequestMethod.POST})
    public String queryForPage(HttpServletRequest request,
                               HttpServletResponse response, Model model,
                               @RequestParam(required=true,defaultValue="1") Integer page){
        long beginTime = System.currentTimeMillis();
        PageHelper.startPage(page, 2);
        List<User> users = userService.queryForPage();
        PageInfo<User> p=new PageInfo<User>(users);
        model.addAttribute("page", p);
        model.addAttribute("users",users);
        logger.info("请求处理结束，耗时：{}毫秒", (System.currentTimeMillis() - beginTime));
        return "user/index";
    }

    @RequestMapping(value = "/getUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public User getUserById(){
        User user = userService.getUser("a1");
        return user;
    }

    @RequestMapping(value = "/insertUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public int insertUser(){
        User user = new User();
        user.setId("a3");
        user.setLoginName("b3");
        user.setLoginPassword("c3");
        userService.insertUser(user);
        return 1;
    }

    @RequestMapping(value = "/updateUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public int updateUser(){
        User user = new User();
        user.setId("a2");
        user.setLoginName("B2");
        user.setLoginPassword("C2");
        this.userService.updateUser(user);
        return 1;
    }
}
